<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <!-- highlight-current  是否高亮选中节点 -->
        <!-- node-key 唯一标识 -->
        <el-tree ref="tree" node-key="id" highlight-current :expand-on-click-node="false" default-expand-all :data="depts" :props="defaultProps" @current-change="selectNodeChange" />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportExcel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template #default="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template #default="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template #default="{row}">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>
              <el-button size="mini" type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            @current-change="changePage"
          />
        </el-row>
      </div>
    </div>
    <!-- 员工导入的组件 -->
    <importExcel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getDepartmentList" />
    <!-- 给员工分配角色 弹出层 -->
    <el-dialog title="分配角色" :visible.sync="showRoleDialog">
      <!--
      roleIds 选中后的角色id数组
      roleList 所有可用的角色列表
       -->
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>

      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="confirm">确定</el-button>
          <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartmentList } from '@/api/department'
import { assignRoles, exportEmployee, getEmployeeDetail, getEmployeeList, getEnableRoleList } from '@/api/employee'
import { translateListToTreeeData } from '@/utils'
import FileSaver from 'file-saver'
import importExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: {
    importExcel
  },
  data() {
    return {
      depts: [
      ],
      defaultProps: {
        children: 'children',
        label: 'name' // 标签文本字段
      },
      // 员工查询的参数对象
      queryParams: {
        departmentId: null,
        page: 1, // 当前页码
        pagesize: 10,
        keyword: '' // 模糊搜索字段
      },
      total: 0, // 记录员工的总数
      list: [],
      showExcelDialog: false, // excel导入的弹出层
      showRoleDialog: false, // 给员工分配角色 弹出层
      roleList: [], // 角色列表
      roleIds: [], // 选中的角色列表
      currentUserId: null // 默认的员工id
    }
  },
  created() {
    this.getDepartmentList()
  },
  methods: {
    // 给员工分配角色
    async btnRole(id) {
      // 1. 显示dialog弹出层
      // this.showRoleDialog = true
      // 2. 查看所有可用的角色列表
      const res = await getEnableRoleList()
      // console.log(res)
      // 3. 渲染视图
      this.roleList = res
      // 4. 获取到员工所拥有的角色信息 - 根据员工的id
      this.currentUserId = id
      const { roleIds } = await getEmployeeDetail(id)
      // 5. 赋值给选中的角色列表
      this.roleIds = roleIds
      // 注意点: 调整弹层显示的时机 (目的: 为了保证渲染完成之后, 再显示)
      this.showRoleDialog = true
    },
    // 确定分配
    async confirm() {
      await assignRoles({
        // 员工id
        id: this.currentUserId,
        // 角色id数组
        roleIds: this.roleIds
      })
      this.$message.success('分配角色成功')
      this.showRoleDialog = false
    },
    // 导出excel
    async exportExcel() {
      // 1. 调用导出员工的接口
      // 二进制流blob
      const res = await exportEmployee()
      console.log(res)
      // 2. fileSaver 下载
      // FileSaver.saveAs(二进制流数据, 文件名)
      FileSaver.saveAs(res, '员工数据.xlsx')
    },
    // 获取部门列表
    async getDepartmentList() {
      const res = await getDepartmentList()
      this.depts = translateListToTreeeData(res, 0)
      // 记录部门中的首个节点
      // TODO (1) 默认选中高亮 (2) 拿着首个部门id, 发请求, 渲染右侧列表的数据
      this.queryParams.departmentId = this.depts[0].id
      console.log(this.depts)
      // 设置首个节点的选中状态
      // 树形组件的渲染是异步的
      this.$nextTick(() => {
        // 目的: 为了保证树形组件渲染完成, 才能进行节点的选中设置
        this.$refs.tree.setCurrentKey(this.queryParams.departmentId)
      })
      this.getEmployeeList()
    },
    // 获取员工列表
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParams)
      this.list = rows
      this.total = total
    },
    // 选中节点 改变
    selectNodeChange(node) {
      this.queryParams.departmentId = node.id
      this.queryParams.page = 1 // 设置第一页
      this.getEmployeeList()
    },
    changeValue() {
      // 单位时间内只执行最后一次
      // this的实例上赋值了一个timer的属性
      clearTimeout(this.timer) // 清理上一次的定时器
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 300)
    },
    // 切换页码
    changePage(newPage) {
      this.queryParams.page = newPage // 赋值新页码
      this.getEmployeeList() // 查询数据
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;

  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }

  .right {
    flex: 1;
    padding: 20px;

    .opeate-tools {
      margin: 10px;
    }

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
